<template>
  <div id="userLogin">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
            v-model="userAccount"
            name="userAccount"
            label="账号"
            placeholder="请输入账号"
            :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
            v-model="userPassword"
            type="password"
            name="userPassword"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 32px;">
        <van-button :loading="isLoading" loading-text="登录中..." plain hairline round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    <div>
      <van-cell-group inset>
        <van-cell title="注册新用户" label="如果还没有账号，请点击右边按钮进行注册">
          <van-button @click="doRegister"  plain hairline round block type="primary" native-type="submit">
            注册
          </van-button>
        </van-cell>
      </van-cell-group>

    </div>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import request from "../../plugins/request.ts";
import {showSuccessToast} from "vant/es";
import {useRoute, useRouter} from "vue-router";

const router = useRouter();
const route = useRoute();
const isLoading = ref(false)
const userAccount = ref('');
const userPassword = ref('');
/**
 * 提交表单执行的方法
 */
const onSubmit = async () => {
  isLoading.value = true
  const res = await request.post("/user/login", {
    "userAccount": userAccount.value,
    "userPassword": userPassword.value
  })
  if (res.data.code === 200 && res.data.data) {
    const toUrl = route.query?.redirect as string ?? '/'
    window.location.href = toUrl
    showSuccessToast('登录成功');
    isLoading.value = false
  } else {
    showSuccessToast("登录失败" + res.data.description)
    isLoading.value = false
  }
};
/**
 * 跳转到注册页面
 */
const doRegister = () => {
  router.push({
    path: '/user/register'
  })
}
</script>

<style scoped>

</style>